//
//  WSUpdateFilterConditionViewController.m
//  microvision
//
//  Created by zhenjingxiong on 2021/3/2.
//  Copyright © 2021 tencent. All rights reserved.
//

#import "WSUpdateFilterConditionViewController.h"
#import "WSUpdateFilterConditionCell.h"
#import "WSDataReportConfig.h"
#import "WSDataReportFilterManager.h"
#import "WSDataReportHelper.h"
#import "WSUpdateFilterConditionDropdownView.h"

static CGFloat const gListViewRowHeight = 65;  // listView的行高

@interface WSUpdateFilterConditionViewController ()
<
UITableViewDataSource,
UIGestureRecognizerDelegate,
WSDataReportDropdownDelegate,
WSDropDownbuttonClickDelegate
>

@property (nonatomic, strong) WSUpdateFilterConditionDropdownView *dropdownView;

@property (nonatomic, strong) UITableView *filterConditionslistView;
@property (nonatomic, strong) UIButton *clearFilterConditionButton;
@property (nonatomic, assign) NSInteger clickIndex; //记录button点击的位置

@end

@implementation WSUpdateFilterConditionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpUI];
}

#pragma mark - setUpUI Method

- (void)setUpUI {
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"更新数据筛选条件";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回"
                                                                             style:UIBarButtonItemStylePlain
                                                                            target:self
                                                                            action:@selector(closeCurrentPage)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"确认"
                                                                             style:UIBarButtonItemStylePlain
                                                                            target:self
                                                                            action:@selector(confirmCurrentCondition)];
    [self.view addSubview:self.filterConditionslistView];
    
    [self.filterConditionslistView  registerClass:[WSUpdateFilterConditionCell class]
                           forCellReuseIdentifier:NSStringFromClass([WSUpdateFilterConditionCell class])];
    
    UITapGestureRecognizer *tapGestureRecognizer = [self createTapGestureRecognizer];
    [self.view addGestureRecognizer:tapGestureRecognizer];
}



#pragma mark - UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WSUpdateFilterConditionCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WSUpdateFilterConditionCell class]) forIndexPath:indexPath];
    WSDataReportFilterItem *filterItem = [WSDataReportConfig instance].dataFilterItemArray[indexPath.row];
    cell.delegate = self;
    cell.index = indexPath.row;
    [cell setUpdateFilterConditionCentent:filterItem];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [WSDataReportConfig instance].dataFilterItemArray.count;
}

#pragma mark - TapGesture Method

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:NSClassFromString(@"UITableViewCellContentView")]) {
        return NO;
    }
    return YES;
}

- (void)clickOnBlankArea {
    [self.view endEditing:YES];
    [self popUpDropdownList:NO];
}

#pragma mark - WSDataReportDropdownDelegate

- (void)didSelectDropdownContent:(NSString *)dropdownContent {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.clickIndex inSection:0];
    WSUpdateFilterConditionCell *cell = [self.filterConditionslistView cellForRowAtIndexPath:indexPath];
    cell.valuesTextField.text = dropdownContent;
    cell.dropDownButton.selected = NO;
    [self.dropdownView removeFromSuperview];
}

#pragma mark - WSDropDownuttonClicknDelegate
- (void)dropDownbuttonClick:(UIButton *)dropDownutton selectIndex:(NSInteger)selectIndex {
    if (self.clickIndex != selectIndex) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.clickIndex inSection:0];
        WSUpdateFilterConditionCell *cell = [self.filterConditionslistView cellForRowAtIndexPath:indexPath];
        cell.dropDownButton.selected = NO;
    }
    self.clickIndex = selectIndex;
    dropDownutton.selected = !dropDownutton.selected;
    [self popUpDropdownList:dropDownutton.isSelected];
}

#pragma mark - Private Method

- (void)closeCurrentPage {
    if ([self.delegete respondsToSelector:@selector(goBackPreviousPage)]) {
        [self.delegete goBackPreviousPage];
    }
}

- (void)confirmCurrentCondition {
    NSMutableArray *filterItemArray = [NSMutableArray array];
    for (int i = 0; i < [WSDataReportConfig instance].dataFilterItemArray.count; i ++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        WSUpdateFilterConditionCell *cell = [self.filterConditionslistView cellForRowAtIndexPath:indexPath];
        WSDataReportFilterItem *filterItem = [WSDataReportConfig instance].dataFilterItemArray[i];
        if ([WSDataReportHelper isBlankString:cell.valuesTextField.text]) {
            filterItem.reportDatafilterValues = @[];
        } else {
            filterItem.reportDatafilterValues = [cell.valuesTextField.text componentsSeparatedByString:@","];
        }
        [filterItemArray addObject:filterItem];
    }
    [WSDataReportConfig instance].dataFilterItemArray = filterItemArray;
    
    if ([self.delegete respondsToSelector:@selector(confirmFilterCondition)]) {
        [self.delegete confirmFilterCondition];
    }
}

- (void)clearFilterCondition {
    for (int i = 0; i < [WSDataReportConfig instance].dataFilterItemArray.count; i ++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        WSUpdateFilterConditionCell *cell = [self.filterConditionslistView cellForRowAtIndexPath:indexPath];
        cell.valuesTextField.text = @"";
    }
    [[WSDataReportFilterManager instance] clearFilterFilterConditions];
}

- (void)popUpDropdownList:(BOOL)isSelected {
    if (!isSelected) {
        [self.dropdownView removeFromSuperview];
        return;
    }
    if (!self.dropdownView.superview) {
        [self.filterConditionslistView addSubview:self.dropdownView];
    }
    WSDataReportFilterItem *filterItem = [WSDataReportConfig instance].dataFilterItemArray[self.clickIndex];
    NSArray *array = filterItem.reportDatafilterDefaultList;
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    CGFloat y = gListViewRowHeight * (self.clickIndex + 1);
    CGFloat height = array.count * 44;
    CGFloat width = filterItem.reportDatafilterMaxWidth;
    CGRect frame;
    if ((y + height) > CGRectGetMaxY(self.view.frame)) {
        CGFloat newY = screenHeight - y - CGRectGetMaxY(self.navigationController.navigationBar.frame);
        frame = CGRectMake(screenWidth - width, y, width, newY);
    } else {
        frame = CGRectMake(screenWidth - width, y, width, height);
    }
    self.dropdownView.frame = frame;
    [self.dropdownView updateDropdownDataSource:array];
}

#pragma mark - Accessor Method

- (UITableView *)filterConditionslistView {
    if (!_filterConditionslistView) {
        _filterConditionslistView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _filterConditionslistView.dataSource = self;
        _filterConditionslistView.rowHeight = gListViewRowHeight;
        _filterConditionslistView.tableFooterView = self.clearFilterConditionButton;
    }
    return _filterConditionslistView;
}

- (UIButton *)clearFilterConditionButton {
    if (!_clearFilterConditionButton) {
        _clearFilterConditionButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
        _clearFilterConditionButton.backgroundColor = [UIColor cyanColor];
        _clearFilterConditionButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_clearFilterConditionButton setTitle:@"清除筛选条件" forState:UIControlStateNormal];
        [_clearFilterConditionButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_clearFilterConditionButton addTarget:self action:@selector(clearFilterCondition)
                              forControlEvents:UIControlEventTouchUpInside];
    }
    return _clearFilterConditionButton;
}

- (WSUpdateFilterConditionDropdownView *)dropdownView {
    if (!_dropdownView) {
        _dropdownView = [[WSUpdateFilterConditionDropdownView alloc] init];
        _dropdownView.delegate = self;
        _dropdownView.backgroundColor = [UIColor yellowColor];
    }
    return _dropdownView;
}

- (UITapGestureRecognizer *)createTapGestureRecognizer {
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                           action:@selector(clickOnBlankArea)];
    tapGestureRecognizer.delegate = self;
    return tapGestureRecognizer;
}

@end
